package com.lvan.fileupload.controller;

import com.lvan.fileupload.bean.ResultMsg;
import com.lvan.fileupload.service.FileService;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author Lvan
 */
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private FileService service;

    @PostMapping("single/upload")
    public ResultMsg fileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResultMsg.error().message("请选择要上传的文件");
        } else {
            String path = service.singleFileUpload(file);
            return !StringUtils.isEmpty(path) ? ResultMsg.success().data("path", path) : ResultMsg.error();
        }
    }

    @PostMapping("batch/upload")
    public ResultMsg batchFileUpload(@RequestParam("file") MultipartFile[] files) {
        if (files == null) {
            return ResultMsg.error().message("请选择要上传的文件");
        } else {
            List list = service.batchFileUpload(files);
            return list.size() > 0 ? ResultMsg.success().data("paths", list) : ResultMsg.error();
        }
    }

    @GetMapping("single/download")
    public ResultMsg fileDownload(String fileName, HttpServletResponse response) {
        if (StringUtils.isEmpty(fileName)) {
            return ResultMsg.error().message("文件不存在");
        } else {
            String message = service.singleFileDownload(fileName, response);
            return StringUtils.isEmpty(message) ? ResultMsg.success() : ResultMsg.error().message(message);
        }
    }

    @GetMapping("batch/download")
    public ResultMsg batchFileDownload(HttpServletResponse response, String[] fileName) {
        if (fileName == null) {
            return ResultMsg.error().message("文件名列表为空");
        } else {
            String message = service.batchFileDownload(fileName, response);
            return StringUtils.isEmpty(message) ? ResultMsg.success() : ResultMsg.error().message(message);
        }
    }

}
